package com.clougence.cloudcanal.dataprocess.datatransform.common;

import com.google.common.io.Resources;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author manburensheng
 */
@Slf4j
public class IpUtil {

    /**
     * 根据IP地址获取城市
     * 每条ip数据段都固定了格式：
     *
     * _城市Id|国家|区域|省份|城市|ISP_
     * 只有中国的数据精确到了城市，其他国家有部分数据只能定位到国家，后前的选项全部是0，
     * 已经包含了全部你能查到的大大小小的国家（请忽略前面的城市Id，个人项目需求）。
     * @param ip
     * @return
     */
    public static String getCityInfo(String ip) throws IOException {

        //        Resource resource = new ClassPathResource("data/ip2region.db");
        //        File file = resource.getFile();

        File file = new File("/home/clougence/cloudcanal/sidecar/data/ip2region.db");
        if (!file.exists()) {
            log.error("Error: Invalid ip2region.db file, filePath：" + file.getPath());
            return null;
        }
        //查询算法 B-tree
        int algorithm = DbSearcher.BTREE_ALGORITHM;
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, file.getPath());
            Method method;
            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
                default:
                    return null;
            }
            DataBlock dataBlock;
            if (!Util.isIpAddress(ip)) {
                System.out.println("Error: Invalid ip address");
                return null;
            }
            dataBlock = (DataBlock) method.invoke(searcher, ip);
            return dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(getCityInfo("82.63.116.213"));
        String cityInfo = IpUtil.getCityInfo("82.63.116.213");
        String[] cityInfoArr = cityInfo.split("\\|");
        System.out.println(cityInfoArr[0]);
        System.out.println(cityInfoArr[0]);
        System.out.println(cityInfoArr[1]);
        System.out.println(cityInfoArr[2]);
        System.out.println(cityInfoArr[3]);
        System.out.println(cityInfoArr[4]);
        System.out.println(getCityInfo("122.224.209.118"));
        System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
        System.out.println(IpUtil.class.getResource("/").getPath() + "data/ip2region.db");
    }

}
